<?php

namespace backend\modules\business\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\business\NewBusinessInspection;

/**
 * NewBusinessInspectionSearch represents the model behind the search form about `common\models\business\NewBusinessInspection`.
 */
class NewBusinessInspectionSearch extends NewBusinessInspection
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'pigid', 'business_personid', 'status', 'is_del','type'], 'integer'],
            [['business_person','createtime', 'address', 'remark','pig.no'], 'safe'],
            [['lat', 'lng'], 'number'],
        ];
    }

    public function attributes()
    {
        // 添加关联字段到可搜索属性集合
        return array_merge(parent::attributes(), ['pig.no']);
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = NewBusinessInspection::find()->alias('ins')->leftJoin(BusinessPig::tableName().' as pig','ins.pigid=pig.id');

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $dataProvider->sort->attributes['pig.no'] = [
            'asc' => ['pig.no' => SORT_ASC],
            'desc' => ['pig.no' => SORT_DESC],
        ];


        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'ins.id' => $this->id,
            'pigid' => $this->pigid,
            'business_personid' => $this->business_personid,
            'lat' => $this->lat,
            'lng' => $this->lng,
            'ins.status' => $this->status,
            'is_del' => $this->is_del,
            'type' => $this->type,
        ]);

        $query->andFilterWhere(['like', 'business_person', $this->business_person])
            ->andFilterWhere(['like', 'address', $this->address])
            ->andFilterWhere(['like', 'pig.no', $this->getAttribute('pig.no')])
            ->andFilterWhere(['FROM_UNIXTIME(createtime, \'%Y-%m-%d\')'=>$this->createtime]);

        return $dataProvider;
    }
}
